//
// Created by LiuYou on 2021/11/25.
//

#include <unistd.h>
#include <sys/epoll.h>
#include <fcntl.h>

#include "Epoll.hpp"


int Epoll::setFdNonBlock(int fd) {
    int oldFdStatus = fcntl( fd, F_GETFL );
    fcntl( fd, F_SETFL, oldFdStatus | O_NONBLOCK );
    return oldFdStatus;
}

void Epoll::addFdToEpoll(int epollFd, int fd, bool isOneShot) {
    setFdNonBlock( fd );
    epoll_event epollEvent{};
    epollEvent.data.fd = fd;
    epollEvent.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
    if (isOneShot) {
        epollEvent.events |= EPOLLONESHOT;
    }
    epoll_ctl( epollFd, EPOLL_CTL_ADD, fd, &epollEvent );
}

void Epoll::deleteFdFromEpoll(int epollFd, int fd) {
    epoll_ctl( epollFd, EPOLL_CTL_DEL, fd, nullptr );
    close( fd );
}

void Epoll::modifyFdFromEpoll(int epollFd, int fd, int epollEvents) {
    epoll_event epollEvent{};
    epollEvent.data.fd = fd;
    epollEvent.events = epollEvents | EPOLLET | EPOLLONESHOT | EPOLLRDHUP;
    epoll_ctl( epollFd, EPOLL_CTL_MOD, fd, &epollEvent );
}


